package com.fuze.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fuze.common.Advice;
import com.fuze.common.CustomException;
import com.fuze.domain.dto.AdministratorsDTO;
import com.fuze.domain.model.Administrators;
import com.fuze.domain.vo.LoginFormVO;
import com.fuze.mapper.AdministratorsMapper;
import com.fuze.service.AdministratorsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author sepc_
 * @date 4/7/2021 16:09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdministratorsServiceImpl implements AdministratorsService {

    final RedisTemplate<String, Object> redisTemplate;

    final AdministratorsMapper administratorsMapper;

    @Override
    public String login(LoginFormVO loginFormVO) {
        log.debug(loginFormVO.toString());
        String token;
        QueryWrapper<Administrators> qw = new QueryWrapper<>();
        qw.eq(Administrators.COL_USERNAME, loginFormVO.getUsername().trim());
        Administrators admin = administratorsMapper.selectOne(qw);
        if (admin == null) {
            throw new CustomException(Advice.ADMIN_NOT_EXIST);
        }
        if (!admin.getPassword().equals(SecureUtil.md5(loginFormVO.getPassword()))) {
            throw new CustomException(Advice.WRONG_PASSWORD);
        }
        token = IdUtil.simpleUUID();
        redisTemplate.opsForValue().set(token, admin, 4, TimeUnit.HOURS);
        return token;
    }

    @Override
    public Boolean existByUsername(String username) {
        return this.administratorsMapper.existByUsername(username);
    }

    @Override
    public int register(AdministratorsDTO administratorsDTO) {
        if (administratorsMapper.existByUsername(administratorsDTO.getUsername())) {
            throw new CustomException(Advice.REPEAT_REGISTRATION);
        }
        Administrators admin = new Administrators();
        BeanUtils.copyProperties(administratorsDTO, admin);
        admin.setPassword(SecureUtil.md5(administratorsDTO.getPassword()));
        return administratorsMapper.insert(admin);
    }

    @Override
    public int update(AdministratorsDTO administratorsDTO) {
        Administrators administrators = new Administrators();
        BeanUtils.copyProperties(administratorsDTO, administrators);
        return this.administratorsMapper.updateById(administrators);
    }
}
